package org.yxing.palpalgps.activity;

import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.ActionBar;
import org.yxing.palpalgps.ActionBar.OnActionBarListener;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.domain.AsyncImageLoader;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.http.AsyncRequest.FetchListener;
import org.yxing.palpalgps.models.User;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.Helper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class UserProfileActivity extends AbstractActivity implements View.OnClickListener, OnActionBarListener {
    
    private static final String TAG = "UserProfileActivity";
    private static final int WHAT_USERINFO = 0;
    private static final int WHAT_ADD_FIREND = 1;
    private static final int WHAT_ADD_BLACKLIST= 4;
    private static final int WHAT_DELETE_BLACKLIST= 5;
    private static final int WHAT_DELETE_FIREND= 2;
    
    private static final int FIREND_STATUS_DEFAULT = 0;
    private static final int FIREND_STATUS_OTHER_APPLY = 1;
    private static final int FIREND_STATUS_ME_APPLY = 2;
    private static final int FIREND_STATUS_FIREND = 3;
    
    private static final String URL_ADD_FRIEND = "friend/add";
    private static final String URL_DELETE_FRIEND = "friend/delete";
    private static final String URL_ADD_BLACKLIST = "blacklist/add";
    private static final String URL_DELETE_BLACKLIST = "blacklist/remove";
    
    private static final int[] relationNames = {R.string.relation_0,
        R.string.relation_1,
        R.string.relation_2,
        R.string.relation_3,
        R.string.relation_4,
        R.string.relation_5,
        R.string.relation_6,
        R.string.relation_7,
        R.string.relation_8
    };
    
    private User mUser;
    
    /**
     * 好友状态
     */
    private int firendStatus;
    /**
     * 是否在黑名单中
     */
    private boolean blacklistStatus;
    /**
     * is can send message
     */
    private boolean messageStatus;
    
    private Handler handler;
    
    //views
    private TextView nameView;
    private ImageView faceView;
    private TextView genderView;
    private TextView birthdayView;
    private TextView relationView;
    //buttons
    private Button firendButton;
    private Button blacklistButton;
    
    private int addFirendStatus;
    private boolean addBlocklistStatus;
    
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_profile);
        setTitle(getString(R.string.user_profile));
        
        nameView = (TextView) findViewById(R.id.name);
        faceView = (ImageView) findViewById(R.id.faceImage);
        genderView = (TextView) findViewById(R.id.gender);
        birthdayView = (TextView) findViewById(R.id.birthday);
        relationView = (TextView) findViewById(R.id.relation);
        firendButton = (Button) findViewById(R.id.firendButton);
        blacklistButton = (Button) findViewById(R.id.blacklistButton);
        
        //绑定点击监听
        firendButton.setOnClickListener(this);
        blacklistButton.setOnClickListener(this);
        getActionBar().setOnActionBarListener(this);
        
        //add action bar
        addActionBarItem(ActionBar.Type.Chat);
        addActionBarItem(ActionBar.Type.Photo);
        
        //开始读取用户信息
        fetchUser();
    }
    
    /**
     * fetch user profile data
     */
    private void fetchUser() {
        if (mUser == null) {
            mUser = new User();
            mUser.setId(getIntent().getStringExtra("uid"));
        }
        String url = "profile/info";
        AsyncRequest ar = new AsyncRequest(this);
        List<BasicNameValuePair> params = OAuth.createAuthParams();
        params.add(new BasicNameValuePair("fuid", mUser.getId()));
        //开始读取用户信息
        ar.fetch(url, params, new FetchListener() {

            public void onComplete(JSONObject response) {
                try {
                    JSONObject result = response.getJSONObject("result");
                    mUser.setFace(result.getString(User.KEY_FACE));
                    mUser.setName(result.getString(User.KEY_NAME));
                    mUser.setBirthday(result.getString(User.KEY_BIRTHDAY));
                    mUser.setGender(result.getString(User.KEY_GENDER));
//                    mUser.setRelation(result.getInt(User.KEY_RELATION));
                    firendStatus = result.getInt("friend_status");
                    blacklistStatus = result.getInt("blacklist_status") != 0;
                    messageStatus = result.getInt("message_status") != 0;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
                displayProfile();
                showButtons();
            }

            public void onError(int code, String msg) {
                
            }
            
        });
    }
    
    /**
     * diaplay profile
     */
    private void displayProfile() {
        nameView.setText(mUser.getName());
        if (mUser.getFace() != null) {
            AsyncImageLoader ail = new AsyncImageLoader();
            String portraitUrl = Helper.getSmallPictureUrl(mUser.getFace());
            ail.loadDrawable(portraitUrl, faceView);
        }
        
        genderView.setText(mUser.getGender().equals("f") ? getString(R.string.female) : getString(R.string.male));
        birthdayView.setText(mUser.getBirthday());
//        relationView.setText(mUser.getRelation());
        
    }
    
    /**
     * show friend operation and blacklist operation button
     */
    private void showButtons() {
        //show firend button
        int resId;
        switch (firendStatus) {
        case FIREND_STATUS_FIREND:
            resId = R.string.delete_firend;
            break;
        case FIREND_STATUS_OTHER_APPLY:
            resId = R.string.accept_firend;
            break;
        default:
            resId = R.string.add_firend;
        }
        firendButton.setVisibility(View.VISIBLE);
        firendButton.setText(getString(resId));
        
        
        blacklistButton.setVisibility(View.VISIBLE);
        if (blacklistStatus) {
            blacklistButton.setText(getString(R.string.delete_blacklist));
        } else
            blacklistButton.setText(getString(R.string.add_balcklist));
        
    }
   
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.firendButton:
            onClickfirendButton();
            break;
        case R.id.blacklistButton:
            if (blacklistStatus) {
                deleteBlacklist();
            } else
                addBlacklist();
            break;
        }
    }
    
    private void onClickfirendButton() {
        int nextStatus;
        int successMsg;
        String url;
        switch (firendStatus) {
        case FIREND_STATUS_DEFAULT:
        case FIREND_STATUS_ME_APPLY:
            addFriend();
            break;
        case FIREND_STATUS_OTHER_APPLY:
            acceptFriend();
            break;
        case FIREND_STATUS_FIREND:
            deleteFriend();
            break;
        }
    }
    
    /**
     * add friend
     */
    private void addFriend() {
        if (firendStatus == FIREND_STATUS_DEFAULT) {
            request(URL_ADD_FRIEND, new RequestCallback() {
                
                public void onSuccess() {
                    displayToast(getString(R.string.toast_add_firend_success));
                    firendStatus = FIREND_STATUS_ME_APPLY;
                }
                
                public void onFailure() {
                    
                }
            });
        } else if (firendStatus == FIREND_STATUS_ME_APPLY) {
            displayToast(getString(R.string.toast_has_apply_firend));
        }
    }
    
    private void acceptFriend() {
        
    }
    
    /**
     * reject friend
     */
    private void rejectFriend() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setMessage(getString(R.string.accept_friend_apply_message));
        alert.setPositiveButton(getString(R.string.accept), new OnClickListener() {
            
            public void onClick(DialogInterface dialog, int which) {
                
            }
        });
        alert.setNegativeButton(getString(R.string.reject), new OnClickListener(){

            public void onClick(DialogInterface dialog, int which) {
                
            }
        });
        alert.create();
        alert.show();
    }
    
    /**
     * delete friend
     */
    private void deleteFriend() {
        
    }
    
    private void addBlacklist() {
        request(URL_ADD_BLACKLIST, new RequestCallback() {
            
            public void onSuccess() {
                displayToast(getString(R.string.toast_add_blacklist_success));
//                blacklistStatus = true;
//                blacklistButton.setText(getString(R.string.delete_blacklist));
                Intent intent = new Intent();
                intent.putExtra(Helper.REFRESH, true);
                setResult(RESULT_OK, intent);
                finish();
            }
            
            public void onFailure() {
                
            }
        });
    }
    
    private void deleteBlacklist() {
        request(URL_DELETE_BLACKLIST, new RequestCallback() {
            
            public void onSuccess() {
                displayToast(getString(R.string.toast_delete_blacklist_success));
                blacklistStatus = false;
                blacklistButton.setText(getString(R.string.delete_blacklist));
            }
            
            public void onFailure() {
                
            }
        });
    }
    
    private void request(String url, final RequestCallback callback) {
        AsyncRequest ar = new AsyncRequest(this);
        List<BasicNameValuePair> params = OAuth.createAuthParams();
        params.add(new BasicNameValuePair("fuid", mUser.getId()));
        ar.fetch(url, params, new FetchListener() {
            
            public void onError(int code, String msg) {
                callback.onFailure();
            }
            
            public void onComplete(JSONObject response) {
                callback.onSuccess();
            }
        });
    }

    public void onActionBarItemClick(int position) {
        switch (position) {
        case 0:
            if (messageStatus) {
                Intent intent = new Intent(this, ChatActivity.class);
                
                intent.putExtra("fuid", mUser.getId());
                intent.putExtra("name", mUser.getName());
                intent.putExtra("portrait", mUser.getFace());
                startActivity(intent);
            }
            break;
        case 1:
            Intent intent = new Intent(this, UserPhotoGridActivity.class);
            intent.putExtra("fuid", mUser.getId());
            startActivity(intent);
            break;
        }
    }
    
    private interface RequestCallback {
        public void onSuccess();
        public void onFailure();
    }
}
